﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace Moonwish.Core
{
    /// <summary>
    /// 实体集合基类，by zhlin 2011-08-09
    /// </summary>
    public abstract class NotificationObjectCollection<T> : KeyedCollection<string, T>, INotifyCollectionChanged
    {

        public abstract new void Add(T item);

        internal protected void BaseAdd(T item)
        {
            BaseAdd(item, true);
        }

        internal protected void BaseAdd(T item, bool notify)
        {
            base.Insert(0, item);
            if (notify)
            {
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, 0));
            }
        }

        public new void Insert(int index, T item)
        {
            Add(item);
        }

        internal protected void BaseInsert(int index, T item)
        {
            base.Insert(index, item);

            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, -1));
        }

        /// <summary>
        /// 增加完成事件。
        /// </summary>
        public event EventHandler<AsyncCompletedEventArgs> AddCompleted;
        /// <summary>
        /// 删除完成事件。
        /// </summary>
        public event EventHandler<AsyncCompletedEventArgs> RemoveCompleted;


        internal protected void BaseRemove(T item)
        {
            base.Remove(item);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, -1));
        }

        public new abstract void Remove(T item);

        public abstract void Remove(IEnumerable<T> items);

        public new abstract void Remove(string key);

        public new void RemoveAt(int index)
        {
            Remove(this[index]);
        }

        public new void Clear()
        {
            base.Clear();
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        public abstract void AcceptChanges();

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (CollectionChanged != null) CollectionChanged(this, e);
        }

        protected void InvokeAddCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (AddCompleted != null)
            {
                AddCompleted(sender, e);
            }
        }

        protected void InvokeRemoveCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (RemoveCompleted != null)
            {
                RemoveCompleted(sender, e);
            }
        }
    }
}
